<?php
/**
 * Created by PhpStorm.
 * User: fengyan
 * Date: 18-1-4
 * Time: 下午4:34
 */

namespace App\Repositories\Addons\Uploads\Drive;

use App\Repositories\Addons\Uploads\ReturnFileInfo;
use App\Repositories\Addons\Uploads\ReturnMsg;

abstract class BaseDrive
{

    /**
     * 上传$_FILES 表单字段
     * @var
     */
    protected $fieldName;

    /**
     * 上传配置信息
     * @var
     */
    protected $config;

    /**
     * 前缀
     * @var string
     */
    protected $prefix;

    /**
     * 保存根路径
     * @var string
     */
    protected $basePath = '';

    /**
     * 错误信息
     * @var
     */
    protected $errorMsg = '';

    /**
     * 上传结果信息
     * @var \App\Repositories\Addons\Uploads\ReturnMsg
     */
    protected $result;



    /**
     * BaseDrive constructor.
     * @param string $basePath 保存根路径
     * @param $fieldName 字段名称
     * @param array $config   配置详情
     * @param string $prefix 前缀
     * @param string $callback 回调方法
     */
    public function __construct(array $config, $fieldName, $basePath = '', $prefix = '', $callback = '')
    {
        $this->fieldName = $fieldName;

        $this->config = $config;

        $this->basePath = $basePath;

        $this->prefix = $prefix;
    }

    /**
     * 获取配置
     * @return array
     */
    public function getConfig() : array
    {
        return $this->config;
    }

    /**
     * 获取上传根路径
     * @return mixed
     */
    protected function getBasePath()
    {
        return $this->basePath;
    }

    /**
     * 重命名文件
     * @return string
     */
    protected function getFullName($fileName)
    {
        //替换日期事件
        $t = time();
        $d = explode('-', date("Y-y-m-d-H-i-s"));
        $format = $this->config["pathFormat"];
        $format = str_replace("{yyyy}", $d[0], $format);
        $format = str_replace("{yy}", $d[1], $format);
        $format = str_replace("{mm}", $d[2], $format);
        $format = str_replace("{dd}", $d[3], $format);
        $format = str_replace("{hh}", $d[4], $format);
        $format = str_replace("{ii}", $d[5], $format);
        $format = str_replace("{ss}", $d[6], $format);
        $format = str_replace("{time}", $t, $format);

        //过滤文件名的非法自负,并替换文件名
        $oriName = substr($fileName, 0, strrpos($fileName, '.'));
        $oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
        $format = str_replace("{filename}", $oriName, $format);

        //替换随机字符串
        $randNum = rand(1, 10000000000) . rand(1, 10000000000);
        if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
            $format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
        }

        $ext = $this->getFileExt($fileName);

        return $format . $ext;
    }

    /**
     * 获取文件扩展名
     * @return string
     */
    protected function getFileExt($fileName)
    {
        return strtolower(strrchr($fileName, '.'));
    }

    public function getResult() : ReturnMsg
    {
        return $this->result;
    }
}